utils.recoverUrlParam()
$(async () => {
  const campaign = 'lucky-bag'
  const av = 'p011'
  const STATUS_OK = 1      // 福袋尚未抢完
  const STATUS_DONE = 2    // 福袋已被抢完
  const STATUS_GRABBED = 3 // 已抢福袋
  const STATUS_EXPIRED = 4 // 福袋过期
  const account = new Account()
  const code = utils.getUrlParam('gid')
  if (code) {
    utils.initAnalytics(av)
    analytics.send({
      event: `${av}_open`,
      attr: {
        _c: utils.getUrlParam('_c')
      }
    })
    utils.initWechatShare({
      title: '【久趣英语】一起抢福袋，瓜分千万奖学金！100%有奖！',
      desc: '纯正北美外教，让4-12岁孩子，爱上英语！',
      link: `${window.location.protocol}//${window.location.host}/wx/lucky-bag?_c=${campaign}&gid=${code}`,
      imgUrl: 'https://static-app.97kid.com/site-student/public/mobile/campaign/luckyBag/icon/ic_share.jpg',
      success: target => {
        analytics.send({
          event: `${av}-share`,
          attr: {target}
        })
      }
    })
    utils.supportPromise(account)
    account.forceLogin = false // 不强制登录
    await getLuckyBagInfo()
  } else {
    utils.goHome()
  }

  // 获取福袋信息
  async function getLuckyBagInfo () {
    let userInfo = null, luckyBagInfo = null
    try {
      userInfo = await account.$getUserInfo()
      console.log(userInfo)
      luckyBagInfo = await fetchLuckyBagInfo(userInfo)
      console.log(luckyBagInfo)
      renderGrabStatus(luckyBagInfo)
      await renderGrabList(luckyBagInfo)
    } catch (err) {
      utils.error(err)
    }
  }

  $('.grab-btn').off('click').on('click', e => {
    fetchGrabLuckyBag().then(getLuckyBagInfo).catch(grabError)

    function grabError (err) {
      console.error(err.message)
      switch (err.code) {
        case 'lucky.bag.grabbed.over':
          resetGrabStatus('.grab-done')
          break
        case 'student.lucky.bag.upper.limit':
          resetGrabStatus('.grab-timeout')
          break
        case 'lucky.bag.expired':
          resetGrabStatus('.grab-over')
          break
        default:
          resetGrabStatus('.grab-ok')
          utils.toast(err.message)
      }
    }
  })

  $('#grab-close').off('click').on('click', e => {
    showGrabSuccess('hide')
  })

  $('.look-other').off('click').on('click', e => {
    analytics.send({
      event: `${av}-look-other`
    })
    utils.goHome()
  })

  // 显示指定的状态页
  function resetGrabStatus (show) {
    $('.grab-ok, .grab-done, .grab-timeout, .grab-class, .grab-old, .grab-new').hide()
    show && $(show).show()
  }

  // 渲染页面状态
  function renderGrabStatus ({status, me}) {
    switch (status) {
      // 未抢完
      case STATUS_OK:
        resetGrabStatus('.grab-ok')
        break
      // 抢完了
      case STATUS_DONE:
        resetGrabStatus('.grab-done')
        break
      // 已抢福袋
      case STATUS_GRABBED:
        if (me && me.type === 1) {
          // 老用户获得奖学金
          $('.grab-old .money').text(Number(me.amount).toFixed(1))
          resetGrabStatus('.grab-old')
          break
        } else if (me && me.type === 2) {
          // 新用户获得1课时
          resetGrabStatus('.grab-new')
          break
        }
      // 福袋过期
      case STATUS_EXPIRED:
        resetGrabStatus('.grab-over')
        break
      default:
        resetGrabStatus('.grab-ok')
        utils.toast('获取福袋状态失败')
    }
  }

  // 渲染中奖列表
  async function renderGrabList ({grabs}) {
    try {
      if (!(grabs && grabs.length > 0)) throw new Error('grabs为空')
      const ids = grabs.map(grab => grab.studentId)
      if (!(ids && ids.length > 0)) throw new Error('ids为空')
      const userList = await fetchUserList(ids)
      if (!(userList && userList.length > 0)) throw new Error('userList为空')
      grabs = grabsMerge(grabs, userList)
      $('.grab-list').empty().append(grabHTML(grabs)).show()
      console.log(grabs)
    } catch (e) {
      console.error(e)
    }

    function grabHTML (grabs) {
      return grabs.map(grabTemplate).join('')
    }

    function grabTemplate (grab) {
      return `
        <div class="grab">
          <img class="avatar" src="${grab.avatar}" onerror="this.src='${CDN_RESOURCE}/mobile/campaign/luckyBag/img/avatar.png'">
          <div class="nickname">${grab.nickname}</div>
          <div class="created-at">${utils.format(new Date(grab.createdAt * 1000), 'yyyy.M.dd hh:mm')}</div>
          <div class="amount ${grab.type === 1 ? '' : 'new'}">${grab.type === 1 ? grab.amount + '元奖学金' : '1课时'}</div>
          <div class="amount-info">${grab.type === 1 ? '奖学金可兑换课时' : '可立即预约1节<br/>北美外教在线课程4人班'}</div>
        </div>
      `
    }

    function findUser (userList, id) {
      return userList.find(user => user.id === id)
    }

    function grabsMerge (grabs, userList) {
      return grabs.map(grab => ({...grab, ...findUser(userList, grab.studentId)}))
    }
  }

  // 显示隐藏弹窗
  function showGrabSuccess (status) {
    if (status === 'show') {
      $('.mask').attr('class', `mask ${status}`)
      setTimeout(() => {
        $('.grab-success').attr('class', `grab-success ${status}`)
      }, 0)
    } else {
      $('.grab-success').attr('class', `grab-success ${status}`)
      setTimeout(() => {
        $('.mask').attr('class', `mask ${status}`)
      }, 250)
    }

  }

  // ===================接口函数==========================

  // 用户信息列表接口
  function fetchUserList (ids) {
    return account.$ajax({
      auth: false,
      type: 'GET',
      path: '/s/students/socials',
      data: {ids: ids.join(',')},
    }).catch(err => ([]))
  }

  // 福袋信息接口
  function fetchLuckyBagInfo (userInfo) {
    return account.$ajax({
      auth: userInfo ? true : false,
      type: 'GET',
      path: `/s/events/luckyBags${userInfo ? '' : '/public'}?code=${utils.utf8ToBase64(code)}`
    })
  }

  // 抢福袋接口
  function fetchGrabLuckyBag () {
    return account.$ajax({
      type: 'PUT',
      path: `/s/events/luckyBags/grab`,
      data: {
        code: utils.utf8ToBase64(code)
      }
    })
  }
})